package me.chan.chatting.server.handler;

import io.netty.channel.Channel;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import lombok.extern.slf4j.Slf4j;
import me.chan.chatting.server.factory.GroupServiceFactory;
import me.chan.chatting.server.model.Group;
import me.chan.chatting.server.msg.GroupCreateRequestMessage;
import me.chan.chatting.server.msg.GroupCreateResponseMessage;
import me.chan.chatting.server.service.GroupService;

import java.util.List;
import java.util.Set;

@Slf4j
@ChannelHandler.Sharable
public class GroupCreateInboundHandler extends SimpleChannelInboundHandler<GroupCreateRequestMessage> {

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, GroupCreateRequestMessage msg) throws Exception {
        Set<String> members = msg.getMembers();
        String groupName = msg.getGroupName();

        GroupService groupService = GroupServiceFactory.getInstance();
        Group group = groupService.createGroup(groupName, members);
        // create successfully
        if (group != null) {
            ctx.writeAndFlush(new GroupCreateResponseMessage(true, groupName + " has created successfully"));
            List<Channel> channels = groupService.getMembersChannel(groupName);
            channels.stream().forEach(ch -> ch.writeAndFlush(new GroupCreateResponseMessage(true,
                                                            "you have been added into the group "+ groupName)));
        } else {
            ctx.writeAndFlush(new GroupCreateResponseMessage(false,
                                        "the group existed already, could not be created again"));
        }
    }
}
